<template>
  <view class="container">
    <view class="header">
      <view class="title">速算练习设置</view>
      <view class="subtitle">四则运算快速计算</view>
    </view>

    <view class="settings-container">
      <!-- 运算类型选择 -->
      <view class="setting-section">
        <view class="section-title">
          <uni-icons color="#007AFF" size="20" type="calculator"></uni-icons>
          <text>运算类型</text>
        </view>
        <view class="option-grid">
          <view
              v-for="operation in operationOptions"
              :key="operation.key"
              :class="{ 'selected': selectedOperations.includes(operation.key) }"
              class="option-item"
              @tap="toggleOperation(operation.key)"
          >
            <view class="option-icon">{{ operation.symbol }}</view>
            <text class="option-text">{{ operation.name }}</text>
          </view>
        </view>
      </view>

      <!-- 数值类型选择 -->
      <view class="setting-section">
        <view class="section-title">
          <text>数值类型</text>
        </view>
        <view class="option-list">
          <view
              v-for="valueType in valueTypeOptions"
              :key="valueType.key"
              :class="{ 'selected': selectedValueTypes.includes(valueType.key) }"
              class="option-item-list"
              @tap="toggleValueType(valueType.key)"
          >
            <view class="option-content">
              <text class="option-name">{{ valueType.name }}</text>
              <text class="option-desc">{{ valueType.description }}</text>
            </view>
            <view class="option-check">
              <uni-icons
                  :color="selectedValueTypes.includes(valueType.key) ? '#007AFF' : '#d0d0d0'"
                  size="20"
                  type="checkmarkempty"
              ></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 题目数量设置 -->
      <view class="setting-section">
        <view class="section-title">
          <text>题目数量</text>
        </view>
        <view class="number-setting">
          <uni-number-box
              :max="50"
              :min="5"
              :value="questionCount"
              @change="onQuestionCountChange"
          ></uni-number-box>
        </view>
      </view>

      <!-- 历史最佳 -->
      <view v-if="bestRecord" class="setting-section">
        <view class="section-title">
          <uni-icons color="#FFD700" size="20" type="star"></uni-icons>
          <text>历史最佳</text>
        </view>
        <view class="best-record">
          <view class="record-item">
            <text class="record-value">{{ bestRecord.score }}</text>
            <text class="record-label">最高分数</text>
          </view>
          <view class="record-item">
            <text class="record-value">{{ bestRecord.accuracy }}%</text>
            <text class="record-label">最高正确率</text>
          </view>
          <view class="record-item">
            <text class="record-value">{{ formatTime(bestRecord.averageTime) }}</text>
            <text class="record-label">最快平均用时</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 开始按钮 -->
    <view class="start-container">
      <button
          :class="{ 'disabled': !canStart }"
          :disabled="!canStart"
          class="start-btn"
          @tap="startPractice"
      >
        <uni-icons color="#ffffff" size="20" type="right"></uni-icons>
        <text>开始练习</text>
      </button>
    </view>
  </view>
</template>

<script>
import Storage from '@/utils/storage.js';
import CommonUtils from '@/utils/common.js';

export default {
  data() {
    return {
      selectedOperations: ['add', 'subtract'],
      selectedValueTypes: ['integer'],
      questionCount: 10,
      bestRecord: null,
      operationOptions: [
        {key: 'add', name: '加法', symbol: '+'},
        {key: 'subtract', name: '减法', symbol: '-'},
        {key: 'multiply', name: '乘法', symbol: '×'},
        {key: 'divide', name: '除法', symbol: '÷'}
      ],
      valueTypeOptions: [
        {key: 'integer', name: '整数', description: '2-5位整数运算'},
        {key: 'decimal', name: '小数', description: '1-2位小数运算'},
        {key: 'percentage', name: '百分数', description: '百分数形式运算'}
      ]
    }
  },
  computed: {
    canStart() {
      return this.selectedOperations.length > 0 &&
          this.selectedValueTypes.length > 0 &&
          this.questionCount >= 5;
    }
  },
  onLoad() {
    this.loadSettings();
    this.loadBestRecord();
  },
  methods: {
    // 切换运算类型
    toggleOperation(operation) {
      const index = this.selectedOperations.indexOf(operation);
      if (index > -1) {
        if (this.selectedOperations.length > 1) {
          this.selectedOperations.splice(index, 1);
        }
      } else {
        this.selectedOperations.push(operation);
      }
      this.saveSettings();
    },

    // 切换数值类型
    toggleValueType(valueType) {
      const index = this.selectedValueTypes.indexOf(valueType);
      if (index > -1) {
        if (this.selectedValueTypes.length > 1) {
          this.selectedValueTypes.splice(index, 1);
        }
      } else {
        this.selectedValueTypes.push(valueType);
      }
      this.saveSettings();
    },

    // 题目数量变化
    onQuestionCountChange(value) {
      this.questionCount = value;
      this.saveSettings();
    },

    // 开始练习
    startPractice() {
      if (!this.canStart) {
        uni.showToast({
          title: '请选择练习设置',
          icon: 'none'
        });
        return;
      }

      const settings = {
        operations: this.selectedOperations,
        valueTypes: this.selectedValueTypes,
        count: this.questionCount
      };

      uni.navigateTo({
        url: `/pages/speed-calc/practice?settings=${encodeURIComponent(JSON.stringify(settings))}`
      });
    },

    // 加载设置
    loadSettings() {
      const settings = Storage.getUserSettings();
      this.selectedOperations = settings.preferredCalcTypes || ['add', 'subtract', 'multiply', 'divide'];
      this.selectedValueTypes = settings.preferredValueTypes || ['integer', 'decimal', 'percentage'];
      this.questionCount = settings.speedCalcQuestionCount || 10;
    },

    // 保存设置
    saveSettings() {
      Storage.saveUserSettings({
        preferredCalcTypes: this.selectedOperations,
        preferredValueTypes: this.selectedValueTypes,
        speedCalcQuestionCount: this.questionCount
      });
    },

    // 加载最佳记录
    loadBestRecord() {
      const records = Storage.getSpeedCalcRecords(20);
      if (records.length > 0) {
        const bestScore = Math.max(...records.map(r => r.score || 0));
        const bestAccuracy = Math.max(...records.map(r => r.accuracy || 0));
        const fastestAvgTime = Math.min(...records.map(r => r.averageTime || Infinity));

        this.bestRecord = {
          score: bestScore,
          accuracy: bestAccuracy,
          averageTime: fastestAvgTime === Infinity ? 0 : fastestAvgTime
        };
      }
    },

    // 格式化时间
    formatTime(seconds) {
      return CommonUtils.formatTime(seconds);
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  background: linear-gradient(135deg, #67e8f9, #38bdf8);
  padding: 60rpx 40rpx 40rpx;
  color: white;
  text-align: center;

  .title {
    font-size: 40rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
  }

  .subtitle {
    font-size: 26rpx;
    opacity: 0.9;
  }
}

.settings-container {
  padding: 40rpx;
}

.setting-section {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 25rpx;

    text {
      font-size: 30rpx;
      font-weight: bold;
      margin-left: 15rpx;
      color: #333;
    }
  }
}

.option-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;

  .option-item {
    flex: 1;
    min-width: 160rpx;
    padding: 25rpx 15rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    text-align: center;
    transition: all 0.3s ease;

    &.selected {
      border-color: #007AFF;
      background-color: #e7f3ff;
    }

    .option-icon {
      font-size: 36rpx;
      font-weight: bold;
      color: #007AFF;
      margin-bottom: 10rpx;
    }

    .option-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.option-list {
  .option-item-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &.selected {
      background-color: #f8f9ff;
      border-radius: 8rpx;
      padding-left: 15rpx;
      padding-right: 15rpx;
    }

    .option-content {
      flex: 1;

      .option-name {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 5rpx;
      }

      .option-desc {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.number-setting {
  display: flex;
  justify-content: center;
}

.best-record {
  display: flex;
  justify-content: space-around;

  .record-item {
    text-align: center;

    .record-value {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #4ecdc4;
      margin-bottom: 8rpx;
    }

    .record-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.start-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx 40rpx;
  background: white;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
}

.start-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #67e8f9, #38bdf8);
  border: none;
  border-radius: 45rpx;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(78, 205, 196, 0.3);

  &.disabled {
    background: #6c757d;
    box-shadow: none;
    opacity: 0.6;
  }

  text {
    margin-left: 10rpx;
  }

  &:active:not(.disabled) {
    transform: scale(0.98);
  }
}
</style>